package io.demo.message.serial;

import com.google.gson.Gson;
import java.nio.charset.StandardCharsets;

public class GsonSerializedObject<T> extends SerializedObject<T> {

  private Gson gson;

  GsonSerializedObject(T object) {
    super(object);
  }

  @Override
  protected void beforeSerialize() {
    gson = new Gson();
  }

  @Override
  protected byte[] doSerialization(T object) {
    return gson.toJson(object).getBytes(StandardCharsets.UTF_8);
  }

  @Override
  public T reverse() {
    @SuppressWarnings("unchecked")
    Class<T> cc = (Class<T>) getObjectClass();
    return gson.fromJson(new String(getByteArray(), StandardCharsets.UTF_8), cc);
  }
}
